<template>
  <div class="system-config-edit">
    <el-card>
      <div slot="header" class="card-header">
        <span>编辑系统配置</span>
        <el-button @click="handleCancel">返回</el-button>
      </div>
      
      <div class="form-container" v-if="configData">
        <el-form ref="form" :model="configData" :rules="rules" label-width="120px">
          <el-form-item label="配置键" prop="configKey">
            <el-input v-model="configData.configKey" placeholder="配置键" disabled></el-input>
          </el-form-item>
          
          <el-form-item label="配置值" prop="configValue">
            <!-- 字符串类型 -->
            <el-input v-if="configData.configType === 'STRING'"
              v-model="configData.configValue" 
              placeholder="请输入配置值"></el-input>
            <!-- 数字类型 -->
            <el-input-number v-else-if="configData.configType === 'NUMBER'"
              v-model="configData.configValue" 
              :min="-999999999" 
              :max="999999999" 
              placeholder="请输入数字"></el-input-number>
            <!-- 布尔类型 -->
            <el-switch v-else-if="configData.configType === 'BOOLEAN'"
              v-model="configData.configValue" 
              active-color="#13ce66" 
              inactive-color="#ff4949"></el-switch>
            <!-- JSON类型 -->
            <el-input v-else-if="configData.configType === 'JSON'"
              v-model="configData.configValue" 
              type="textarea" 
              placeholder="请输入JSON配置值" 
              :rows="5"></el-input>
          </el-form-item>
          
          <el-form-item label="配置类型" prop="configType">
            <el-select v-model="configData.configType" placeholder="请选择配置类型">
              <el-option label="STRING" value="STRING"></el-option>
              <el-option label="NUMBER" value="NUMBER"></el-option>
              <el-option label="BOOLEAN" value="BOOLEAN"></el-option>
              <el-option label="JSON" value="JSON"></el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="描述" prop="description">
            <el-input v-model="configData.description" placeholder="请输入描述信息" type="textarea" :rows="2"></el-input>
          </el-form-item>
          
          <el-form-item label="状态">
            <el-switch 
              v-model="configData.isEnabled" 
              active-color="#13ce66" 
              inactive-color="#ff4949"
            ></el-switch>
          </el-form-item>
          
          <el-form-item label="创建时间">
            <el-input v-model="configData.createTime" disabled></el-input>
          </el-form-item>
          
          <el-form-item label="更新时间">
            <el-input v-model="configData.updateTime" disabled></el-input>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleSubmit">提交</el-button>
            <el-button @click="handleCancel">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <div v-else class="loading-container">
        <el-empty description="加载配置信息失败" />
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'SystemConfigEdit',
  data() {
    // 自定义验证规则
    const validateConfigValue = (rule, value, callback) => {
      if (!value && value !== false && value !== 0) {
        callback(new Error('请输入配置值'));
      } else if (this.configData && this.configData.configType === 'JSON') {
        try {
          // 验证JSON格式
          JSON.parse(value);
          callback();
        } catch (e) {
          callback(new Error('请输入有效的JSON格式'));
        }
      } else {
        callback();
      }
    };

    return {
      configData: null,
      rules: {
        configKey: [
          { required: true, message: '请输入配置键', trigger: 'blur' }
        ],
        configType: [
          { required: true, message: '请选择配置类型', trigger: 'change' }
        ],
        configValue: [
          { validator: validateConfigValue, trigger: 'blur' }
        ]
      }
    };
  },
  mounted() {
    this.loadConfigData();
  },
  methods: {
    // 加载配置数据
    loadConfigData() {
      const id = this.$route.query.id;
      if (id) {
        this.$api.systemConfigApi.getById(id).then(res => {
          const data = res && res.data || null;
          if (data) {
            // 深拷贝，避免直接修改响应数据
            this.configData = { ...data };
            // 根据不同类型的数据进行适当转换
            if (this.configData.configType === 'NUMBER') {
              this.configData.configValue = Number(this.configData.configValue);
            } else if (this.configData.configType === 'BOOLEAN') {
              this.configData.configValue = this.configData.configValue === 'true' || this.configData.configValue === true;
            }
          } else {
            this.$message.error('获取配置信息失败');
          }
        }).catch(err => {
          console.error('获取系统配置失败:', err);
          this.$message.error('获取配置信息失败');
        });
      } else {
        this.$message.error('参数错误');
      }
    },
    
    // 提交表单
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 准备提交数据
          const submitData = { ...this.configData };
          
          // 处理JSON类型数据
          if (submitData.configType === 'JSON') {
            try {
              // 确保JSON格式正确
              submitData.configValue = JSON.parse(submitData.configValue);
            } catch (e) {
              this.$message.error('请输入有效的JSON格式');
              return;
            }
          }
          
          // 发送更新请求
          this.$api.systemConfigApi.update(this.configData.id, submitData)
            .then(data => {
              this.$message.success('更新成功');
              this.$router.push('/system-config');
            })
            .catch(error => {
              this.$message.error('更新失败: ' + error.message);
            });
        } else {
          return false;
        }
      });
    },
    
    // 取消编辑
    handleCancel() {
      this.$router.push('/system-config');
    }
  }
};
</script>

<style scoped>
.system-config-edit {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
}

.form-container {
  max-width: 800px;
  margin: 0 auto;
}

.loading-container {
  padding: 40px 0;
  text-align: center;
}
</style>